import time
from selenium.webdriver.common.by import By

from selenium.webdriver.support.wait import WebDriverWait
import logging

logger = logging.getLogger(__name__)


def user_login(driver, username, password):
    driver.get('http://116.62.63.211/shop/user/loginInfo.html')
    el_name = driver.find_element(By.XPATH, '/html/body/div[4]/div/div[2]/div[2]/div/div/div[1]/form/div[1]/input')
    el_name.send_keys(username)
    el_password = driver.find_element(By.XPATH,
                                      '/html/body/div[4]/div/div[2]/div[2]/div/div/div[1]/form/div[2]/div/input')
    el_password.send_keys(password)
    el_btn = driver.find_element(By.XPATH, '/html/body/div[4]/div/div[2]/div[2]/div/div/div[1]/form/div[3]/button')
    el_btn.click()
    logger.info(f"使用账号{username}进行登录")

    # time.sleep(2)
    # 显式等待
    # 1、创建WebDriverWait对象
    wait = WebDriverWait(driver, 10)

    # 2、在函数中判断就绪条件
    def f(d):
        # 如果就绪，返回True
        # 如果没有就绪，返回False
        el = d.find_element(By.XPATH, '/html/body/div[10]/div/p')
        if el.text == "":
            return False
        return True

    # 3、把函数传递给对象，进行等待
    wait.until(f)

    el = driver.find_element(By.XPATH, '/html/body/div[10]/div/p')
    logger.info(f"登录结果:{el.text}")
    return el.text


def get_msg(driver):
    xpath = '//p[@class="prompt-msg"]'
    wait = WebDriverWait(driver, 10)

    def f(a):
        el = driver.find_element(By.XPATH, xpath)
        if el.text != "":
            return True
        else:
            return False

    wait.until(f)

    el = driver.find_element(By.XPATH, xpath)
    return el.text
